<?php
/**
 * Created by PhpStorm.
 * User: dev
 * Date: 11/11/14
 * Time: 4:30 PM
 */




class Admin_Utility_Backup_Controller extends Admin_Controller {

    public $restful = true;

    public function __construct()
    {
        parent::__construct();
        //--Your Code --//
        $this->theme->set_theme("admin") ;
        $this->theme->set_layout("default") ;
    }


    public function get_index(){

        $this->theme->append_metadata('<script src= '.URL::to('')."themes/admin/assets/js/backup.js".'></script>');
        $this->theme->title("Database : Backup");
        $data['backup'] = DB::table('backup_log')->order_by('id', 'desc')->take(25)->get();
        return $this->theme->render('admin::utility.dbbackup',$data);
    }

    public function post_index(){
        //$r = DatabaseBackup::fire();

        $host = Config::get('database.connections.mysql.host');
        $database = Config::get('database.connections.mysql.database');
        $username = Config::get('database.connections.mysql.username');
        $password = Config::get('database.connections.mysql.password');
        $backupPath = path('storage') . "backup/";
        $backupFileName = $database . "_" . date("Y_m_d_H_i_s") . '.sql';

        //for linux replace the path with /usr/local/bin/mysqldump (The path might varies).
        $path = "/usr/local/bin/mysqldump";
        //with password
        $command = "mysqldump" . " -u" . $username . " -p" . $password . " " . $database . " > " . $backupPath . $backupFileName;


        system($command);

        //--Insert Database (table name: backup_log)
        $fileSize = File::size($backupPath . $backupFileName);
        DB::table('backup_log')->insert(array(
            'file'         => trim($backupFileName),
            'size'          => $fileSize
        ));

        return Redirect::back();
    }

    public function get_download($file=''){
        return Response::download(path('storage').'/backup/' . $file);
    }

    public function get_delete($id){
        $backup = DB::table('backup_log')->where('id', '=',$id)->first();
        $backupPath = path('storage') . "database/";

        unlink($backupPath.$backup->file);

        DB::query("delete from backup_log where id = $id");
        return Redirect::back();
    }

} 